package com.ruoyi.dl.controller.wechat;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.dl.domain.DlGameGrade;
import com.ruoyi.dl.domain.DlOrders;
import com.ruoyi.dl.domain.DlOrdersGoods;
import com.ruoyi.dl.domain.DlUser;
import com.ruoyi.dl.service.IDlGameGradeService;
import com.ruoyi.dl.service.IDlOrdersGoodsService;
import com.ruoyi.dl.service.IDlOrdersService;
import com.ruoyi.dl.service.IDlUserService;
import com.ruoyi.dl.uitls.DwUtil;
import com.ruoyi.dl.uitls.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发单商品Controller
 *
 * @author ruoyi
 * @date 2020-12-28
 */
@Controller
@RequestMapping("/wechat/dl/goods")
@CrossOrigin(allowCredentials = "true")
public class WeChatDlOrdersGoodsController extends BaseController {

    @Autowired
    private IDlOrdersGoodsService iDlOrdersGoodsService;

    @Autowired
    private IDlUserService dlUserService;

    @Autowired
    private IDlGameGradeService dlGameGradeService;

    @Autowired
    private IDlUserService iDlUserService;

    @Autowired
    private IDlOrdersService iDlOrdersService;

    @Log(title = "商品订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(DlOrdersGoods dlOrdersGoods, Integer userId) {
        if (userId != null) {
            DlUser dlUser = dlUserService.selectDlUserById(userId);
            dlUser.setFreeze(dlUser.getFreeze().add(dlOrdersGoods.getOrderPrice()));
            dlUser.setBalance(dlUser.getBalance().subtract(dlOrdersGoods.getOrderPrice()));
            dlUserService.updateDlUser(dlUser);
        }
        dlOrdersGoods.setGoodsNumber(Tool.generateUniqueKey("FD"));
        dlOrdersGoods.setOrderPrice(dlOrdersGoods.getOrderPrice().multiply(new BigDecimal(0.8)));
        return toAjax(iDlOrdersGoodsService.insertDlOrdersGoods(dlOrdersGoods));
    }

    /**
     * 查询所有商单列表
     *
     * @return
     */
    @PostMapping("/selectDlOrdersGoodsALL")
    @ResponseBody
    public AjaxResult selectDlOrdersGoodsALL(DlOrdersGoods dlOrdersGoods) {
        List<DlOrdersGoods> dlOrdersGoodsList = iDlOrdersGoodsService.newSelectDlOrdersGoodsList(dlOrdersGoods);
        return AjaxResult.success("成功", dlOrdersGoodsList);
    }

    /**
     * 查询所有未接商单列表排序
     *
     * @param dlOrdersGoods 商单信息
     * @return 结果
     */
    @PostMapping("/selectSearchDlOrdersGoodsALLSortService")
    @ResponseBody
    public AjaxResult selectSearchDlOrdersGoodsALLSortService(DlOrdersGoods dlOrdersGoods) {
        switch (dlOrdersGoods.getFieldName()) {
            case "b":
                dlOrdersGoods.setFieldName("g.order_price");
                dlOrdersGoods.setSortName("desc");
                break;
            case "c":
                dlOrdersGoods.setFieldName("g.order_price");
                dlOrdersGoods.setSortName("asc");
                break;
            case "d":
                dlOrdersGoods.setFieldName("g.bz_money");
                dlOrdersGoods.setSortName("asc");
                break;
            case "e":
                dlOrdersGoods.setFieldName("g.time_limit");
                dlOrdersGoods.setSortName("desc");
                break;
        }
        if ("0".equals(dlOrdersGoods.getGameArea())) {
            dlOrdersGoods.setGameArea("");
        }
        List<DlOrdersGoods> dlOrdersGoodsList = iDlOrdersGoodsService.newSelectSearchDlOrdersGoodsALLSortService(dlOrdersGoods);
        return AjaxResult.success("成功", dlOrdersGoodsList);
    }


    /**
     * 查询所有未接商单列表
     *
     * @param dlOrdersGoods 信息
     * @return 结果
     */
    @PostMapping("/newSelectSearchDlOrdersGoodsNotInOrders")
    @ResponseBody
    public AjaxResult newSelectSearchDlOrdersGoodsNotInOrders(DlOrdersGoods dlOrdersGoods) {
        return AjaxResult.success("成功", iDlOrdersGoodsService.newSelectSearchDlOrdersGoodsNotInOrders(dlOrdersGoods));
    }

    /**
     * 查询所有已接商单列表
     *
     * @param dlOrdersGoods 信息
     * @return 结果
     */
    @PostMapping("/newSelectSearchDlOrdersGoodsInOrders")
    @ResponseBody
    public AjaxResult newSelectSearchDlOrdersGoodsInOrders(DlOrdersGoods dlOrdersGoods) {
        return AjaxResult.success("成功", iDlOrdersGoodsService.newSelectSearchDlOrdersGoodsInOrders(dlOrdersGoods));
    }

    /**
     * 根据用户id查询个人我接受的商单列表
     *
     * @param userId     用户id
     * @param ordersType 订单状态
     * @return
     */
    @PostMapping("/selectDlOrdersGoodsByUserId")
    @ResponseBody
    public AjaxResult selectDlOrdersGoodsByUserId(Integer userId, Integer ordersType, Integer pageIndex, Integer pageSize) {
        return AjaxResult.success("成功", iDlOrdersGoodsService.selectDlOrdersGoodsByUserId(userId, ordersType, pageIndex, pageSize));
    }

    /**
     * 根据用户id查询个人我发布的的商单列表
     *
     * @param userId     发布人id
     * @param ordersType 订单状态
     * @param pageIndex  索引
     * @param pageSize   条数
     * @return
     */
    @PostMapping("/selectDlOrdersGoodsByFBUserId")
    @ResponseBody
    public AjaxResult selectDlOrdersGoodsByFBUserId(Integer userId, Integer ordersType, Integer pageIndex, Integer pageSize) {
        return AjaxResult.success("成功", iDlOrdersGoodsService.selectDlOrdersGoodsByFBUserId(userId, ordersType, pageIndex, pageSize));
    }

    /**
     * 根据id查询商单
     *
     * @param Id id
     * @return 商单
     */
    @PostMapping("/selectDlOrdersGoodsById")
    @ResponseBody
    public AjaxResult selectDlOrdersGoodsById(Integer Id) {
        if (Id != null) {
            DlOrdersGoods dlOrdersGoods = iDlOrdersGoodsService.newSelectDlOrdersGoodsById(Id);
            return AjaxResult.success("成功", dlOrdersGoods);
        }
        return AjaxResult.error("失败");

    }

    /**
     * 根据用户id进行接单
     *
     * @param userId   用户id
     * @param Id       未接商单id
     * @param password 密码
     * @return 结果
     */
    @PostMapping("/selectJDByUserId")
    @ResponseBody
    public AjaxResult selectJDByUserId(Integer userId, Integer Id, Integer password) {
        DlUser dlUser = iDlUserService.selectDlUserById(userId);
        if (!dlUser.getZfPassward().equals(password.toString())) {
            return AjaxResult.error("支付密码错误，请重新输入！！", 1000);
        }
        DlOrdersGoods dlOrdersGoods = iDlOrdersGoodsService.selectDlOrdersGoodsById(Id);
        BigDecimal frozenMoney = dlOrdersGoods.getBzMoney().add(dlOrdersGoods.getXlMoney());
        // 判断余额是否小于（保证金+效率金）
        if (dlUser.getBalance().compareTo(frozenMoney) == -1) {
            return AjaxResult.error("余额不足请充值！！", 2000);
        } else {
            // 更新用户的余额和冻结资金
            DlUser updateUserInfo = new DlUser();
            updateUserInfo.setId(dlUser.getId());
            updateUserInfo.setBalance(dlUser.getBalance().subtract(frozenMoney));
            updateUserInfo.setFreeze(dlUser.getFreeze().add(frozenMoney));
            iDlUserService.updateDlUser(updateUserInfo);
            // 插入接单信息
            DlOrders dlOrders = new DlOrders();
            dlOrders.setOrdersGoodsId(dlOrdersGoods.getId());
            dlOrders.setOrdersNumber(Tool.generateUniqueKey("DL"));
            dlOrders.setUserId(userId);
            dlOrders.setOrdersType(1);
            iDlOrdersService.insertDlOrders(dlOrders);
        }
        return AjaxResult.success("接单成功！！！");
    }

    /**
     * 计算
     *
     * @param nowDan
     * @param targetDan
     * @param trainType
     * @param gameId
     * @return
     */
    @PostMapping("/calculates")
    @ResponseBody
    @CrossOrigin
    public Map<String, Object> calculates(String nowDan, String targetDan, String trainType, String gameId) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (nowDan.indexOf("[") != -1) {
                nowDan = nowDan.replace("[", "");
                nowDan = nowDan.replace("]", "");
            }
            if (targetDan.indexOf("[") != -1) {
                targetDan = targetDan.replace("[", "");
                targetDan = targetDan.replace("]", "");
            }
            DlGameGrade dlGameGrade = new DlGameGrade();
            dlGameGrade.setTrainType(Integer.valueOf(trainType));
            dlGameGrade.setGameId(Integer.valueOf(gameId));
            Map<String, Object> gzmap = dlGameGradeService.mySelectKeyValue(dlGameGrade);
            BigDecimal nowyx = DwUtil.myCal(gzmap, Integer.valueOf(trainType), nowDan);
            BigDecimal targetyx = DwUtil.myCal(gzmap, Integer.valueOf(trainType), targetDan);

            map.put("yxjiage", targetyx.subtract(nowyx));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    //根据id删除未接单的商单(撤销)
    @PostMapping("/delete")
    @ResponseBody
    @Transactional
    public AjaxResult deleteGoodsById(Integer goodsId, Integer userId) {
        if (goodsId != null && userId != null) {
            DlOrdersGoods dlOrdersGoods = iDlOrdersGoodsService.selectDlOrdersGoodsById(goodsId);
            DlUser dlUser = dlUserService.selectDlUserById(userId);
            dlUser.setFreeze(dlUser.getFreeze().subtract(dlOrdersGoods.getOrderPrice()));
            dlUser.setBalance(dlUser.getBalance().add(dlOrdersGoods.getOrderPrice()));
            dlUserService.updateDlUser(dlUser);
        }
        return toAjax(iDlOrdersGoodsService.deleteDlOrdersGoodsById(goodsId));
    }


}
